<?php

// Namespace

namespace Loop;


/**
 * CListHelper helps to manipulate lists of objects
 *
 * @package		Loop
 * @category	Helper
 */

class CListHelper
{
	/**
	 * Sets-up everything needed by a PagePicker
	 *
	 * @param	int		$page			The ID of the current page (e.g. 0, 1, 2…)
	 * @param	int		$nbPages		The number of pages to display
	 * @param	int		$nbItems		The total number of items	 
	 * @param	int		$previousPage	The ID of the previous page
	 * @param	int		$startPage		The ID of the first page
	 * @param	int		$endPage		The ID of the last page 
	 * @param	int		$nextPage		The ID of the next page
	 */
	
	public function setupPagePicker(&$page, &$nbPages = null, $nbItems = null, &$previousPage = null, &$startPage = null, &$endPage = null, &$nextPage = null)
	{
		// Define the total number of pages
		
		$nbItemsPerPage = pref('[Loop]/ui/nbItemsPerPage');
		
		$nbPages = floor($nbItems / $nbItemsPerPage); 
		
		if (($nbItems % $nbItemsPerPage) > 0)
		{
			$nbPages++;
		}
		
		
		// Define how many pages buttons will be displayed
		// Ensure that this number is odd and between 3-9
		
		$nbPagesPerPicker = pref('[Loop]/ui/nbPagesPerPicker');
		
		// Check if the number of pages is enough for the page picker first
		
		if ($nbPages > $nbPagesPerPicker)
		{
			if ($nbPagesPerPicker < 3)
			{
				$nbPagesPerPicker = 3;
			}
			else if ($nbPagesPerPicker > 9)
			{
				$nbPagesPerPicker = 9;
			}
			else if (($nbPagesPerPicker % 2) == 0)
			{
				$nbPagesPerPicker++;
			}
		}
		else
		{
			$nbPagesPerPicker = $nbPages;
		}
		
		// What is going to be the increment?
		
		$i = 2;
		
		if ($nbPagesPerPicker > 3)
		{
			$i += ($nbPagesPerPicker - 3) / 2;
		}
		
		
		// Define how many pages buttons will be displayed before and after the current page button
		
		if ($nbPages > 2)
		{
			$endPage = $page + ($nbPagesPerPicker - $i);
		} 
		else
		{
			$endPage = $nbPages;
		}
		
		// Define the start page, if the total page less than the number of page per picker always start from 1
		
		$startPage = ($nbPages >= $nbPagesPerPicker) ? $page - ($nbPagesPerPicker - $i) : 1;
		
		if ($endPage > $nbPages)
		{
			$startPage -= abs($endPage - $nbPages);
			$endPage = $nbPages;
		}
		
		if ($startPage < 1)
		{
			if ($nbPages > 2)
			{
				$endPage += abs(1 - $startPage);
			}
			$startPage = 1;
		}
		
		
		// Make sure the page number is within boundaries
		
		if ($page < $startPage)
		{
			$page = $startPage;
		}
		
		if ($page > $endPage)
		{
			$page = $endPage;
		}
		
		
		// Page must at least be equal to 1
		
		if ($page < 1)
		{
			$page = 1;
		}
		
		
		// Define previous page
		
		$previousPage = $page - 1;
		
		if ($previousPage < 1)
		{
			$previousPage = 1;
		}
		
		
		// Define next page
		
		$nextPage = $page + 1;
		
		if ($nextPage > $nbPages)
		{
			$nextPage = $nbPages;
		}
	}
}

?>
